import axios from "axios";

// 初始化api sdk
export default async function fetchInitCode(appId, keyId, userDataTypes, baseUrl) {
    const time = sessionStorage.getItem('initCodeTime');
    if (time) {
        // 有code时直接运行
        const lastTime = new Date().getTime() - time;
        if (lastTime < 300000) {
            console.log("initCodeTime生效中，无需获取新的initCode");
            await forAuthPop(appId, keyId, userDataTypes, baseUrl);
            return
        }
    }

    await axios
        .get(`${baseUrl}/getInitCode/${keyId}`, {timeout: 20000})
        .then((res) => {
            const {initCode} = res.data.data;
            sessionStorage.setItem('initCodeTime', new Date().getTime());

            if (!initCode) return;

            // 初始化api sdk
            sc.config({
                debug: false, // 是否开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来
                appId: appId, // 在统一 APP 开放平台服务器申请的 appId
                initCode: initCode
            });

            //注册成功之后执行
            sc.ready(() => {
                console.log("初始化完成，校验是否弹出授权");
                // 校验是否需要弹起授权
                forAuthPop(appId, keyId, userDataTypes, baseUrl)
            });

            sc.error(() => {
                sc.toast({
                    text: '网络正在开小差~~',
                });
                sessionStorage.setItem('initCodeTime', '')
            })
        })
        .catch(function () {
            sc.toast({
                text: '网络正在开小差~~',
            });
            setTimeout(() => {
                sc.goback();
                if (window.loadingInfo) {
                    window.loadingInfo.close()
                }
            }, 1500)
        })
}

// 弹起授权
async function forAuthPop(appId, keyId, userDataTypes, baseUrl) {
    const time = sessionStorage.getItem(`userAccessTokenTime${keyId}`);
    if (time) {
        if (new Date().getTime() - time < 2 * 60 * 60 * 1000) {
            console.log("userAccessTokenTime生效中  无需授权");
            const userAccessToken = JSON.parse(sessionStorage.getItem(`userAccessToken${code}`));
            await fetchUserInfo(appId, keyId, userDataTypes, baseUrl, userAccessToken);
            return
        }
    }

    // 获取授权
    sc.userAuth({
        appId: appId,
        userDataTypes: userDataTypes
    }, (ress) => {
        if (ress.code === 0) {
            // 根据得到的requestCode 进行校验
            axios.post(`${baseUrl}/checkRequestCode`, {
                requestCode: ress.data.requestCode,
                keyId: keyId,
                appId: appId
            })
                .then((response) => {
                    // 授权成功
                    sessionStorage.setItem(`userAccessToken${keyId}`, JSON.stringify(response.data.data.userAccessToken));
                    sessionStorage.setItem(`userAccessTokenTime${keyId}`, new Date().getTime());
                    // fetchUserInfo(appId, keyId, userDataTypes, baseUrl, response.data.data.userAccessToken, that, fun)
                })
        } else {
            setTimeout(() => {
                sc.goback();
                if (window.loadingInfo) {
                    window.loadingInfo.close()
                }
            }, 1500);
            if (ress.code === -10001) {
                sc.toast({
                    text: '初始化失败',
                });
            } else if (ress.code === -10002) {
                sc.toast({
                    text: '您已拒绝授权~~',
                });
            } else if (ress.code === -10003) {
                sc.toast({
                    text: '您还未登录~~',
                });
            } else {
                sc.toast({
                    text: '网络正在开小差~~',
                });
            }
        }
    })
}
